package com.lvyq.javaprint.view.index;

import com.lvyq.javaprint.constant.TrayConstant;
import com.lvyq.javaprint.exception.GlobalCache;
import com.lvyq.javaprint.util.PrintUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;

import javax.print.PrintService;

/**
 * @author lvyq 打印列表视图
 * @version 1.0
 * Create by 2025-01-09 15:00
 */
public class PrintServerView {
    /**
     * @description 创建打印列表视图
     * @author lvyq
     * @throws
     * @return VBox
     * @time 2025-01-07 16:25
     */
    public static VBox createPrintBoxView() {
        VBox printBox = new VBox();
        //宽度小于scrollPane宽度，避免出现水平滑动框
        printBox.setPrefWidth(TrayConstant.stageW-TrayConstant.pane_Hor_Margin*2-3.50);
        printBox.setPrefHeight(TrayConstant.stageH-TrayConstant.pane_Vet_Margin*2-28.00);
        printBox.setStyle("-fx-padding: 3;-fx-border-color: rgba(0.0,0.0,0.0,0.2);-fx-border-width: 2;-fx-border-radius: 4");
        ///单选框
        PrintService[] printServices = PrintUtils.printServices();
        ToggleGroup toggleGroup = new ToggleGroup();
        String service = PrintUtils.defaultPrintService();

        if (printServices.length>0){
            for (int i = 0; i < printServices.length; i++) {
                PrintService printService = printServices[i];
                String name = printService.getName();
                RadioButton radioButton = new RadioButton(name);
                //固定宽度可使横向滑动块不出现
               //radioButton.setMaxWidth(TrayConstant.stageW-TrayConstant.pane_Hor_Margin*2-5.50);
                radioButton.setUserData(name);
                if (name.equals(service)){
                    radioButton.setSelected(true);
                    //默认打印服务
                    GlobalCache.put("defaultPrintService",printService);
                }
                radioButton.setToggleGroup(toggleGroup);
                printBox.getChildren().add(radioButton);
                //服务缓存
                GlobalCache.put(name,printService);
            }
        }else {
            printBox.getChildren().add(new Label("没有找到打印服务"));
        }
        toggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> observableValue, Toggle toggle, Toggle t1) {
                RadioButton radioButton = (RadioButton) toggle.getToggleGroup().getSelectedToggle();
                String checkPrintService = radioButton.getUserData().toString();
                PrintService curPrintService=(PrintService)GlobalCache.get(checkPrintService);
                //服务缓存
                GlobalCache.put("defaultPrintService",curPrintService);

            }
        });
        return printBox;
    }
}
